package com.jic.member.impl;

import com.alibaba.fastjson.JSON;
import com.jic.common.base.vo.RestResult;
import com.jic.member.constant.enums.DeleteFlagEnum;
import com.jic.member.entity.*;
import com.jic.member.enums.GetTypeEnum;
import com.jic.member.mapper.*;
import com.jic.member.request.*;
import com.jic.member.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员等级管理-成长值规则主表
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-04-08 03:50:24
 */
@Service
@Slf4j
public class MememberGrowthObtainServiceImpl implements MememberGrowthObtainService {
    @Resource
    private MememberGrowthRuleMapper mememberGrowthRuleMapper;
    @Resource
    MememberGrowthActionMapper mememberGrowthActionMapper;
    @Resource
    MememberGrowthOrderRechargeService mememberGrowthOrderRechargeService;
    @Resource
    MememberGrowthOrderMoneyService mememberGrowthOrderMoneyService;
    @Resource
    MememberGrowthAppraisalService mememberGrowthAppraisalService;
    @Resource
    private MememberUserMapper mememberUserMapper;
    @Resource
    MemMemberGrowthBaseMapper mememberGrowthBaseMapper;
    @Resource
    private MememberGrowthLogMapper mememberGrowthLogMapper;
    @Resource
    private MememberGradeMapper mememberGradeMapper;



    @Override
    public RestResult<Boolean> obtainOrConsumptionGrowth(ObtainOrConsumptionGrowthRequest request) {
        try {
            //查询当前用户
            MememberUser mememberUser = mememberUserMapper.queryByPrimaryKey(Long.valueOf(request.getMemberId()));
            if (mememberUser == null) {
                return RestResult.error("9999", "不存在Id为【" + request.getMemberId() + "】的用户");
            }
            if (mememberUser.getStatus().equals(0)) {
                return RestResult.error("9999", "当前账号已冻结");
            }
            //单次赠送成长值数量
            Long giveGrowthVal = new Long(0);

            //单日成长值上限
            Long giveGrowthMaxNum = new Long(0);

            String obtainMode = request.getObtainMode();

            //查询当前类型的生效的成长值规则
            MememberGrowthRule growthRule = mememberGrowthRuleMapper.queryGrowthRuleByDeptIdAndDeptTypeAndObtainMode(request.getObtainMode(), request.getAdminOperate());
            if (growthRule == null) {
                return RestResult.error("9999", "当前平台没有此类型的规则");
            }

            if (GetTypeEnum.REGISTER_HANDLESEL.getCode().equals(obtainMode)
                    || GetTypeEnum.SHARE_HANDLESEL.getCode().equals(obtainMode)
                    || GetTypeEnum.LIKE_HANDLESEL.getCode().equals(obtainMode)
                    || GetTypeEnum.SHOW_ORDER_HANDLESEL.getCode().equals(obtainMode)
                    || GetTypeEnum.COLLECT_HANDLESEL.getCode().equals(obtainMode)
                    ) {
                //注册-分享-点赞-晒单-收藏赠送 查询mem_member_growth_action 表

                MememberGrowthAction mememberGrowthAction = mememberGrowthActionMapper.queryGrowthActionByGrowthIdAndObtainMode(obtainMode, growthRule.getId());
                if (mememberGrowthAction == null) {
                    log.error("查询mem_member_growth_action 为空 请求参数:{},{}", obtainMode, growthRule.getId());
                    return RestResult.error("9999", "当前平台没有此类型的规则");
                }
                //获取单次赠送的成长值 和 每日赠送成长值的上限

                giveGrowthVal = mememberGrowthAction.getGiveGrowthVal();

                giveGrowthMaxNum = mememberGrowthAction.getGiveGrowthMaxNum();
            } else if (GetTypeEnum.EVALUATE_HANDLESEL.getCode().equals(obtainMode)) {
                //评价  mem_member_growth_appraisal
                List<MememberGrowthAppraisal> appraisalList = mememberGrowthAppraisalService.queryAppraisalByGrowthRuleId(growthRule.getId());
                if (request.getWhetherPic() == null) {
                    return RestResult.error("9999", "获取方式为评价时 whetherPic字段必传");
                }
                if (request.getWhetherPic().equals(1)) {
                    //带图
                    if (appraisalList.size() > 1) {
                        MememberGrowthAppraisal mememberGrowthAppraisal = appraisalList.get(1);
                        giveGrowthVal = mememberGrowthAppraisal.getGiveGrowthVal().longValue();
                        giveGrowthMaxNum = mememberGrowthAppraisal.getGiveGrowthMaxNum().longValue();
                    } else {
                        if (!appraisalList.get(0).getWhetherPic().equals(1)) {
                            return RestResult.error("9999", "当前规则未设置带图成长值规则");
                        }
                        MememberGrowthAppraisal mememberGrowthAppraisal = appraisalList.get(0);
                        giveGrowthVal = mememberGrowthAppraisal.getGiveGrowthVal().longValue();
                        giveGrowthMaxNum = mememberGrowthAppraisal.getGiveGrowthMaxNum().longValue();
                    }
                } else {
                    //不带图
                    if (appraisalList.size() > 1) {
                        giveGrowthVal = appraisalList.get(0).getGiveGrowthVal().longValue();
                        giveGrowthMaxNum = appraisalList.get(0).getGiveGrowthMaxNum().longValue();
                    } else {
                        if (!appraisalList.get(0).getWhetherPic().equals(2)) {
                            return RestResult.error("9999", "当前规则未设置不带图成长值规则");
                        }
                        MememberGrowthAppraisal mememberGrowthAppraisal = appraisalList.get(0);
                        giveGrowthVal = mememberGrowthAppraisal.getGiveGrowthVal().longValue();
                        giveGrowthMaxNum = mememberGrowthAppraisal.getGiveGrowthMaxNum().longValue();
                    }
                }
            } else if (GetTypeEnum.ORDER_HANDLESEL.getCode().equals(obtainMode)
                    || GetTypeEnum.PAY_HANDLESEL.getCode().equals(obtainMode)) {
                //下单 充值赠送
                List<MememberGrowthOrderRecharge> orderRechargeList = mememberGrowthOrderRechargeService.query(new MememberGrowthOrderRecharge() {{
                    setObtainMode(obtainMode);
                    setGrowthRuleId(growthRule.getId());
                    setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                }});

                MememberGrowthOrderRecharge mememberGrowthOrderRecharge = orderRechargeList.get(0);
                giveGrowthMaxNum = mememberGrowthOrderRecharge.getGiveGrowthMaxNum();

                List<MememberGrowthOrderMoney> orderMoneyList = mememberGrowthOrderMoneyService.query(new MememberGrowthOrderMoney() {{
                    setOrderId(mememberGrowthOrderRecharge.getId());
                    setGrowthRuleId(growthRule.getId());
                }});

                if (orderMoneyList.size() > 1) {
                    //阶梯赠送
                    //根据满多少选排序
                    //根据创建时间倒排
                    orderMoneyList = orderMoneyList.stream().filter(orderMoney -> orderMoney.getConsumeMoney().compareTo(request.getOrderMoney()) < 1)
                            .sorted(Comparator.comparing(MememberGrowthOrderMoney::getConsumeMoney)).collect(Collectors.toList());

                    giveGrowthVal = orderMoneyList.get(orderMoneyList.size() - 1).getGiveGrowthVal();
                } else {
                    //每消费
                    BigDecimal consumeMoney = orderMoneyList.get(0).getConsumeMoney();
                    giveGrowthVal  = orderMoneyList.get(0).getGiveGrowthVal();
                    BigDecimal divide = request.getOrderMoney().divide(consumeMoney, 0, BigDecimal.ROUND_DOWN);
                    Long num = divide.longValue();
                    if (num < 1) {
                        return RestResult.error("9999", "当前消费未达到赠送条件");
                    }
                    giveGrowthVal = giveGrowthVal * num;
                }
            }
            //判断操作类型 2:消耗 3获取
            if (request.getActionType() == 2L) {
                //走消耗成长值方法
                return memberConsumption(request, giveGrowthVal, mememberUser);
            } else {
                return memberObtain(request, giveGrowthVal, giveGrowthMaxNum, mememberUser);
            }
        } catch (Exception e) {
            log.error("获取/消耗成长值失败===>>>>>>{}", e);
            return RestResult.error("9999", "服务器错误...");
        }
    }

    /**
     * 获取成长值
     *
     * @param request
     * @param giveGrowthVal
     * @param giveGrowthMaxNum
     * @param mememberAction
     * @return
     */
    private RestResult<Boolean> memberObtain(ObtainOrConsumptionGrowthRequest request, Long giveGrowthVal, Long giveGrowthMaxNum, MememberUser mememberAction) {
        //查询当前平台每日成长值上限 mem_member_growth_base
        MememberGrowthBase base = mememberGrowthBaseMapper.queryBaseByDeptIdAndDeptType(request.getAdminOperate());
        Long growthDayMax = null;
        if (base != null) {
            growthDayMax = base.getGrowthDayMax();
        }
        //查询用户当天累计的成长值是否超过每日上限
        Long countGrowthRuleVal = mememberGrowthLogMapper.queryDaySumByMemId(mememberAction.getId(), 1, request.getObtainMode());
        Long sumGrowthRuleVal = mememberGrowthLogMapper.queryDaySumByMemId(mememberAction.getId(), 1, null);
        //是否超规则上限
        countGrowthRuleVal = countGrowthRuleVal == null ? 0L : countGrowthRuleVal;
        if (giveGrowthMaxNum != null && giveGrowthMaxNum < (countGrowthRuleVal + giveGrowthVal)) {
            giveGrowthVal = giveGrowthMaxNum - countGrowthRuleVal;
            if (giveGrowthVal == 0L) {
                return RestResult.error("9999", "当前用户达到规则最大成长值，无法继续获取");
            }
        }
        if (growthDayMax != null && growthDayMax < (sumGrowthRuleVal + giveGrowthVal)) {
            giveGrowthVal = growthDayMax - sumGrowthRuleVal;
            if (giveGrowthVal == 0L) {
                return RestResult.error("9999", "当前用户达到平台最大成长值，无法继续获取");
            }
        }
        BigDecimal zero = new BigDecimal(mememberAction.getGrowthNumber() ==null? 0 : mememberAction.getGrowthNumber());
        BigDecimal growthValue = new BigDecimal(giveGrowthVal);

        Long updateGrowthNumber =zero.add(growthValue).longValue() ;
        //没有超过上限增加成长值
        MememberUser mememberActionUpdate = new MememberUser();
        mememberActionUpdate.setId(mememberAction.getId());
        mememberActionUpdate.setGrowthNumber(updateGrowthNumber);
        mememberUserMapper.update(mememberActionUpdate);

        //新增用户成长值记录
        MememberGrowthLog mememberGrowthLog = new MememberGrowthLog();
        mememberGrowthLog.setGrowthRuleVal(giveGrowthVal);
        mememberGrowthLog.setObtainMode(Long.valueOf(request.getObtainMode()));
        mememberGrowthLog.setMemberId(mememberAction.getId());
        mememberGrowthLog.setAddOrReduce(1);
        mememberGrowthLog.setCreateTime(new Date());
        mememberGrowthLog.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        mememberGrowthLog.setChangeType(1L);
        mememberGrowthLog.setGrowthNumber(updateGrowthNumber);
        mememberGrowthLogMapper.insert(mememberGrowthLog);
        //调用crm
        RestResult restResult = updateMemGrade(request, updateGrowthNumber, mememberAction.getGrowthNumber(), mememberAction);
        return restResult;
    }


    /**
     * 消耗成长值
     *
     * @return
     */
    private RestResult<Boolean> memberConsumption(ObtainOrConsumptionGrowthRequest request, Long giveGrowthVal, MememberUser mememberAction) {
        //修改总成长值
        //获取用户总成长值
        Long growthNumber = mememberAction.getGrowthNumber();
        growthNumber = growthNumber == null ? 0L : growthNumber;
        Long updateGrowthNumber = growthNumber - giveGrowthVal;

        if (updateGrowthNumber < 0L) {
            updateGrowthNumber = 0L;
        }

        MememberUser mememberActionUpdate = new MememberUser();
        mememberActionUpdate.setId(mememberAction.getId());
        mememberActionUpdate.setGrowthNumber(updateGrowthNumber);
        mememberUserMapper.update(mememberActionUpdate);

        //新增用户成长值记录
        MememberGrowthLog mememberGrowthLog = new MememberGrowthLog();
        mememberGrowthLog.setGrowthRuleVal(giveGrowthVal);
        mememberGrowthLog.setObtainMode(Long.valueOf(request.getObtainMode()));
        mememberGrowthLog.setMemberId(mememberAction.getId());
        mememberGrowthLog.setAddOrReduce(2);
        mememberGrowthLog.setChildId(request.getAdminOperate().getChildId());
        mememberGrowthLog.setCreateTime(new Date());
        mememberGrowthLog.setCreator(request.getAdminOperate().getOperator());
        mememberGrowthLog.setDeptId(request.getAdminOperate().getDeptId());
        mememberGrowthLog.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
        mememberGrowthLog.setDeptType(request.getAdminOperate().getDeptType().getCode());
        mememberGrowthLog.setChangeType(2L);
        mememberGrowthLog.setGrowthNumber(updateGrowthNumber);
        mememberGrowthLogMapper.insert(mememberGrowthLog);
        //调用crm
        RestResult restResult = updateMemGrade(request, updateGrowthNumber, mememberAction.getGrowthNumber(), mememberAction);
        return restResult;
    }


    private RestResult updateMemGrade(ObtainOrConsumptionGrowthRequest request, Long finalGrowVal, Long originalVal, MememberUser mememberAction) {
        MememberGrade mememberGrade = new MememberGrade();
        mememberGrade.setGrowRangeStart(finalGrowVal);
        mememberGrade.setGrowRangeEnd(finalGrowVal);

        log.info("新增/消耗会员积分成长值==》查询会员等级表==》入参,{}", mememberGrade);
        List<MememberGrade> gradeList = mememberGradeMapper.query(mememberGrade);
        if (gradeList == null || gradeList.size() != 1) {
            //取上限最大的一个
            MememberGrade mememberGradeMax = mememberGradeMapper.queryMaxGradeByDeptId();
            MememberGrade mememberGradeMin = mememberGradeMapper.queryMinGradeByDeptId();
            if (mememberGradeMax == null || mememberGradeMin == null) {
                RestResult<Boolean> success = RestResult.success(true);
                success.setMsg("当前平台下不存在等级,用户等级本次不发生变动");
                return success;
            }
            if (finalGrowVal > mememberGradeMax.getGrowRangeEnd()) {
                gradeList.add(mememberGradeMax);
            } else if (finalGrowVal < mememberGradeMin.getGrowRangeStart()) {
                gradeList.add(mememberGradeMin);
            }
        }
        MememberGrade grade = gradeList.get(0);
        //修改业务表会员等级信息
        mememberAction.setMemberGradeId(grade.getId());
        mememberAction.setGrowthNumber(finalGrowVal);
        log.info("新增/消耗会员积分成长值==》会员业务主表修改==》入参,{}", mememberAction);
        long update = mememberUserMapper.update(mememberAction);
        log.info("Update table - [mem_member_action] info is:=========>,{}", JSON.toJSONString(mememberAction));
        return RestResult.success(true);
    }

}